import axios from "axios";

export default {
    namespaced: true,
    state: {
        cartList: []
    },
    mutations: {
        updateCartList(state, newCartList) {
            state.cartList = newCartList
        },

        updateCount(state, obj) {
            //根据id找到对应的对象，将count更新
            const goods = state.cartList.find(item => item.id === obj.id)
            goods.count = obj.newCount
        }
    },
    actions: {
        async getCartList(context) {
            // 将服务器数据同步到vuex
            const res = await axios.get('http://localhost:3000/cart')
            context.commit('updateCartList', res.data)
        },

        async updateCountAsync(context, obj) {
            // console.log(obj)
            // 将修改更新同步到服务器
            await axios.patch(`http://localhost:3000/cart/${obj.id}`, {
                count: obj.newCount
            })
            // 将修改更新同步到vuex
            context.commit('updateCount', obj)
        }
    },
    getters: {
        total(state) {
            return state.cartList.reduce((preValue, item) => {
                return preValue + item.count
            }, 0);
        },
        totalPrice(state) {
            return state.cartList.reduce((preValue, item) => {
                return preValue + item.price * item.count
            }, 0);
        }
    },
    modules: {}
}
